package com.forum.controller.user;

import com.forum.constant.JwtClaimsConstant;
import com.forum.properties.JwtProperties;
import com.forum.result.Result;
import com.forum.service.UserService;
import com.forum.utils.JwtUtil;
import com.forum.vo.UserInfoStatisticsVO;
import com.forum.vo.UserInfoVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

import static com.forum.constant.MessageConstant.MODIFICATION_BACKGROUND;

@Slf4j
@Api(tags = "用户登录注册接口")
@RestController("UserUserController")
@RequestMapping("/user/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @ApiOperation("根据token查询用户")
    @GetMapping("/ByUser")
    public Result<UserInfoVO> getUserById(String token){
        log.info("传过来的token,{}",token);

        Long userId = getUserId(token);

        log.info("解析过,{}",userId);

        UserInfoVO userInfoVO = userService.getById(userId);
        return Result.success(userInfoVO);
    }



    @ApiOperation("根据id查询用户")
    @GetMapping("/{id}")
    public Result<UserInfoVO> getUserInfo(@PathVariable("id") Long userId){
        UserInfoVO userInfoVO = userService.getById(userId);
        return Result.success(userInfoVO);
    }

    @ApiOperation("查询用户详细信息包括收藏，发布，喜欢")
    @GetMapping("/userInfo")
    public Result<UserInfoStatisticsVO> getUserStatistics(String token){
        log.info("查询的用户id：{}",token);
        Long id = getUserId(token);
        UserInfoStatisticsVO userInfoStatisticsVO = userService.getUserStatistics(id);
        return Result.success(userInfoStatisticsVO);
    }


    /**
     * 修改用户背景
     * @param token
     * @param backgroundImage
     * @return
     */
    @ApiOperation("修改用户背景")
    @PutMapping("/background")
    public Result putBackground(String token, String backgroundImage) throws IOException {
        log.info("查询的用户id：{},{}",token,backgroundImage);
        Long id = getUserId(token);
        userService.putBackground(id,backgroundImage);
        return Result.success(MODIFICATION_BACKGROUND);
    }
    /**
     * 根据token解析用户id
     * @param token
     * @return
     */
    private Long getUserId(String token) {
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        return userId;
    }
}
